

const PEDDING = "pedding";
const FULFILLED = "fulfilled";
const REJECTED = "rejected";

class MyPromise {
  public value;
  public reason;

  public status = PEDDING;

  public successCallbackList = [];

  public failCallbackList = [];

  constructor(exector) {
    try {
      exector(this.resolve, this.reject);
    } catch (error) {
      this.reject(error);
    }
  }

  resolve = (val) => {
    if (this.status !== PEDDING) return;
    // 负责更改状态
    this.status = FULFILLED;
    this.value = val;
    // 调用注册的所有成功回调
    while (this.successCallbackList.length) {
      this.successCallbackList.shift()();
    }
  };


  reject = (reason) => {
    if (this.status !== PEDDING) return;
    // 负责更改状态
    this.status = REJECTED;
    this.reason = reason;
    // 调用注册的所有失败回调
    while (this.failCallbackList.length) {
      this.failCallbackList.shift()();
    }
  };

  then(successCallback, failCallback) {
    successCallback =
      typeof successCallback === "function"
        ? successCallback
        : (value) => value;
    failCallback =
      typeof failCallback === "function" ? failCallback : (reason) => reason;
    let promise2 = new MyPromise((resolve, reject) => {
      // setTimout 是为了模拟浏览器的异步调用
      if (this.status === FULFILLED) {
        setTimeout(() => {
          try {
            let x = successCallback(this.value);
            resolvePromiseLike(promise2, x, resolve, reject);
          } catch (error) {
            reject(error);
          }
        }, 0);
      } else if (this.status === REJECTED) {
        setTimeout(() => {
          try {
            let x = failCallback(this.reason);
            resolvePromiseLike(promise2, x, resolve, reject);
          } catch (error) {
            reject(error);
          }
        }, 0);
      } else {
        this.successCallbackList.push(() => {
          setTimeout(() => {
            try {
              let x = successCallback(this.value);
              resolvePromiseLike(promise2, x, resolve, reject);
            } catch (error) {
              reject(error);
            }
          }, 0);
        });
        this.failCallbackList.push(() => {
          setTimeout(() => {
            try {
              let x = failCallback(this.reason);
              resolvePromiseLike(promise2, x, resolve, reject);
            } catch (error) {
              reject(error);
            }
          }, 0);
        });
      }
    });
    return promise2;
  }

  catch(failCallback) {
    return this.then(undefined, failCallback);
  }

  finally(callback) {
    return this.then(
      (value) => {
        return MyPromise.resolve(callback()).then(
          () => value);
      },
      (reason) =>
        MyPromise.resolve(callback()).then(
          () => {
            throw reason;
          })
    );
  }

  static all(list) {
    let res = [];
    return new MyPromise((resolve, reject) => {
      function addData(key, value) {
        res[key] = value;
        if (res.length === list.length) {
          resolve(res);
        }
      }
      for (let i = 0, len = list.length; i < len; i++) {
        let current = list[i];
        if (current instanceof MyPromise) {
          current.then((value) => addData(i, value), reject);
        } else {
          addData(i, current);
        }
      }
    });
  }

  static race(list) {
    return new MyPromise((resolve, reject) => {
      for (let i = 0, len = list.length; i < len; i++) {
        let current = list[i];
        if (current instanceof MyPromise) {
          current.then(resovle, reject);
        } else {
          resolve(current)
        }
      }
    });
  }

  static resolve(data) {
    if (data instanceof MyPromise) return data;
    return new MyPromise((resolve) => resolve(data));
  }

  static reject(data) {
    if (data instanceof MyPromise) return data;
    return new MyPromise((_, reject) => reject(data));
  }
}

function resolvePromiseLike(promise, x, resolve, reject) {
  // 检测循环调用，是为了控制异步调用中错误使用带来的副作用
  if (promise === x) reject(new TypeError("chaining cycle"));
  // 遇到promise需要拆解，等待结果
  if (x instanceof MyPromise) {
    x.then(resolve, reject);
  } else {
    resolve(x);
  }
}
